import { create } from "zustand";
import { initialNodes } from "../views/advanced-use/state-management/nodes";
import { initialEdges } from "../views/advanced-use/state-management/edge";
import { applyEdgeChanges, applyNodeChanges } from "@xyflow/react";
import { addEdge } from "@xyflow/react";

const useColorStore = create((set, get) => ({
  nodes: initialNodes,
  edges: initialEdges,
  setNodes: (nodes) => {
    set({ nodes });
  },
  setEdges: (edges) => {
    set({ edges });
  },
  onNodesChange: (changes) => {
    set({
      nodes: applyNodeChanges(changes, get().nodes),
    });
  },
  onEdgesChange: (changes) => {
    set({
      edges: applyEdgeChanges(changes, get().edges),
    });
  },
  onConnect: (conn) => {
    set({
      edges: addEdge(conn, get().edges),
    });
  },
  updateNodeColor: (nodeId, color) => {
    set({
      nodes: get().nodes.map((node) => {
        if (node.id === nodeId) {
          return { ...node, data: { ...node.data, color } }; // it's important to create a new object here, to inform React Flow about the changes
        }
        return node;
      }),
    });
  },
}));

export default useColorStore;
